<script setup>
import {ref, reactive} from "vue";
import {Lock, User} from "@element-plus/icons-vue";
import {encryptionData} from "@/utils/encrypt_aes.js";
import SvgIcon from "@/components/iconfont/SvgIcon.vue";
import {ElMessage} from "element-plus";
import {login} from "@/api/index.js";
import useUserInfoStore from '@/store/user.js'
import {useRouter} from "vue-router";
const router = useRouter();
const store = useUserInfoStore();
const ruleForm = reactive({
  username: "",
  password: "",
  code: "",
  uuid: "",
})
// 对数据进行校验
const rules = reactive({
  username: [
    {
      required: true,
      message: "请输入用户名",
      trigger: "blur",//当用户在对应的输入框中输入完成并且焦点离开输入框时，相关的验证规则会生效，检查输入的合法性，并在必要时显示相应的错误消息
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      min: 6,
      message: "密码长度不能少于6位",
      trigger: "blur",
    },
  ],

  code: [
    {
      required: true,
      message: "请输入验证码",
      trigger: "blur",
    },
    {
      min: 4,
      max: 4,
      message: "验证码长度位4位",
      trigger: "blur",
    },
  ],
});
// 获取图片验证码
//1.获取uuid
function generateUUID() {
  let d = new Date().getTime();
  let uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
      /[xy]/g,
      function (c) {
        let r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
      }
  );
  return uuid;
}

let uuid = generateUUID();
// 2.获取验证码图片路径
let verify_src = ref(
    `/api/user/logcode/${uuid}/?data=${new Date().getTime()}`
);

// 3.点击验证码图片，重新获取
const get_verification_image = () => {
  verify_src.value = `/api/user/logcode/${uuid}/?data=${new Date().getTime()}`;
};

const ruleFormRef = ref();
const submitForm = async (rulFormRef) => {
  if (!rulFormRef) return;
  ruleForm.uuid = uuid;
  await rulFormRef.validate(async (valid) => {
    if (valid) {
      await submitUserLogin();
    }
  })
}
const encryptionData_password = ref();
const submitUserLogin = async () => {
  if(!encryptionData_password.value){
    encryptionData_password.value = ruleForm.password
  }
  ruleForm.password =encryptionData(ruleForm.password)
  try {
    const res  = await login(ruleForm)
    if(res.status===201){
      // 通过pinia存储后端返回的用户数据以及token (存储token到localStorage)
      store.SetUserInfo(res.res_data)
      // 跳转页面到首页
      await router.push("/home")
      ElMessage.success('登录成功')
    }else{
      ElMessage.error(res.msg)
      get_verification_image()
      if(res.status===400){
        ruleForm.code = ''
        ruleForm.password = encryptionData_password.value
      }else if(res.status===404){
        for(let i in ruleForm){
          ruleForm[i] = ''
        }
      }
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后尝试登录！')
    ruleForm.password  = encryptionData_password.value
    ruleForm.code = ''
    get_verification_image()
  }
}

</script>

<template>
  <div class="login">
    <h1>ChatPulse</h1>
    <div class="form-container">
      <h2>欢迎登录</h2>
      <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          status-icon
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
      >
        <el-form-item prop="username">
          <el-icon color="#409efc" :size="30">
            <User/>
          </el-icon>
          <el-input type="text" v-model="ruleForm.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item prop="password">
          <el-icon color="#409efc" :size="30">
            <Lock/>
          </el-icon>
          <el-input type="password" v-model="ruleForm.password" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item prop="code" class="code">
          <el-icon size="30px" color="#409efc">
            <SvgIcon iconName="icon-yanzhengma1"/>
          </el-icon>
          <el-input type="text" v-model="ruleForm.code" placeholder="请输入4位验证码"/>
          <img
              style="width: 100px; height:32px"
              :src="verify_src"
              @click="get_verification_image" alt=""
          />
        </el-form-item>
        <p class="register-link-box">
          <router-link to="/register" class="register-link">没有账号？点击注册</router-link>
        </p>
        <el-form-item id="button">
          <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>


<style lang="less" scoped>
.login {
  width: 100%;
  height: 100%;
  background-image: url("@/assets/img/background.png");
  /*将元素的定位方式设为固定定位，使其相对于浏览器窗口固定位置，不随页面滚动而移动*/
  position: fixed;
  background-size: 100% 100%;
  align-content: center;
  h1{
    color: #928383;
  }
  .form-container {
    width: 600px;
    margin: 0 auto;/*水平居中*/
    padding: 20px;
    border: 1px solid #1d3043;
    box-shadow: 0 0 12px rgba(0, 0, 0, 0.12);
    border-radius: 14px;
    h2 {
      padding: 20px 200px 0 200px;
      font-size: 30px;
      color: #928383;
      margin: 0 0 0 0;
    }

    .el-form {
      margin-top: 30px;
      margin-left: 30px;

      .el-form-item {
        margin-top: 40px;

        .el-input {
          width: 300px;
        }
      }

      .code {
        .el-input {
          width: 190px;
        }

        img {
          width: 100px;
          height: 32px;
          margin-left: 10px;
        }
      }

      #button {
        .el-button {
          width: 365px;
        }
      }
    }
    .register-link-box {
      display: flex;
      margin: 20px 20px 10px 20px;
      .register-link {
        color: #409EFF; /* Example color */
        font-size: 20px;
      }
    }
  }
}
</style>